package com.cqs.leetcode.heap;

import com.cqs.leetcode.ds.ArraysUtils;

import java.util.PriorityQueue;

/**
 * lixw
 * 2021/9/4
 **/
public class SmallestK {

    public int[] smallestK(int[] arr, int k) {
        if (k == 0) return new int[]{};
        PriorityQueue<Integer> q = new PriorityQueue<>((o1, o2) -> o2 - o1);
        for (int i : arr) {
            if (q.size() == k) {
                if (q.peek() <= i) continue;
                q.poll();
            }
            q.add(i);
        }
        return q.stream().mapToInt(value -> value).toArray();
    }

    public static void main(String[] args) {
        int[] test = new int[]{ 1,3,5,7,2,4,6,8};
        int[] ints = new SmallestK().smallestK(test, 3);

        System.out.println( ArraysUtils.formatInts(ints));
    }
}
